import 'package:flutter_app/network/Loading.dart';
import 'package:flutter_app/utils/image_file_info_utils.dart';
import 'package:flutter_app/utils/video_compress_utils.dart';
import 'package:get/get.dart';
import 'package:image_pickers/image_pickers.dart';

import 'photo_select_state.dart';

class PhotoSelectLogic extends GetxController {
  final PhotoSelectState state = PhotoSelectState();

  late String dirName;
  @override
  void onInit() {
    super.onInit();
    dirName = Get.arguments;
  }

  @override
  void onReady() {
    super.onReady();
    if (dirName.isEmpty) {
      return;
    }
    getDirFile(dirName);
  }

  // 获取指定文件夹下的 图片和视频
  Future<void> getDirFile(String dirName) async {
    List<ImageFileInfo> imageFileInfo = await ImageFileInfoUtils().getFileInfoInGroupId(dirName);
    List<String> times = [];
    imageFileInfo.forEach((info) {
      times.add(info.time ?? "");
    });
    // 去重复
    times = times.toSet().toList();

    List<PhotoGalleryInfo> list = [];

    times.forEach((time) {
      PhotoGalleryInfo photoGalleryInfo = new PhotoGalleryInfo();
      photoGalleryInfo.list = [];

      // 设置标题
      photoGalleryInfo.title = time;

      imageFileInfo.where((info) => time == info.time).forEach((info) {
        photoGalleryInfo.list?.add(info);
      });

      list.add(photoGalleryInfo);
    });
    Loading.dismiss();
    state.entity = list;
    update();
  }

  // 获取缩略图
  Future<String> getThumbnail(String path) async {
    final thumbnailFile = await VideoCompressUtils().getFileThumbnail(path);
    return thumbnailFile.path;
  }

  // 保存
  void save() {
    List<Media> list = [];
    state.entity?.forEach((entity) {
      entity.list?.forEach((info) {
        if (info.isChose.value) {
          Media media = new Media();
          media.path = info.path;
          media.thumbPath = info.thumbnail;
          if (info.type == "image") {
            media.galleryMode = GalleryMode.image;
          } else {
            media.galleryMode = GalleryMode.video;
          }
          list.add(media);
        }
      });
    });

    Get.back(result: list);
  }

  @override
  void onClose() {}
}
